'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url client/user/kh/my_invite_user 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		const db = uniCloud.database();
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			_
		} = util;
		let {
			uid,
			bean_number, //每邀请一个新用户奖励多少
			type
		} = data;
		let res = {
			code: 0,
			msg: ""
		};

		//=======兼容老版本:bean_number缺失时，默认100=======
		if (!bean_number) {
			bean_number = 100
		}
		//=======兼容老版本:bean_number缺失时，默认100=======

		// 业务逻辑开始-----------------------------------------------------------
		let my_invite_user = await db.collection('uni-id-users').where({
			invite_code: userInfo.my_invite_code
		}).orderBy('register_date', 'desc').limit(20).get()
		res.userlist = my_invite_user.data

		let user_total = await db.collection('uni-id-users').where({
			invite_code: userInfo.my_invite_code
		}).count()
		res.total = user_total.total

		//剩余可领取的奖励次数 = 邀请总人数 - 已领取奖励次数
		res.surplus_times = user_total.total - userInfo.reward_times
		//避免出现负数
		if (res.surplus_times < 0) {
			res.surplus_times = 0;
			return res;
		}

		if (type == "reward") {
			//领取金豆数量
			let change_bean = res.surplus_times * bean_number * 1;

			//此方法腾讯云和阿里云都支持
			let updateUser = await vk.baseDao.updateAndReturn({
				dbName: "uni-id-users",
				whereJson: {
					_id: userInfo._id
				},
				dataJson: {
					reward_times: _.inc(res.surplus_times),
					balance: _.inc(change_bean)
				}
			});

			console.log("updateUser=", updateUser.balance);


			//添加金豆收支明细
			const addBeanDetail_qiandao = await db.collection('a_jindou_detail').add({
				user_id: userInfo._id,
				nickname: userInfo.nickname || "匿名用户",
				os_name: originalParam.context.osName || "未知", //用户当时的系统
				change_num: change_bean, //扣除的金豆数量
				change_reason: "邀请奖励" + change_bean + "金豆",
				type: "income", //类型：expend:支出,income:收入。
				tfid: userInfo.tfid,
				invite_code: userInfo.invite_code,
				middleman_id: userInfo.middleman_id,
				province: userInfo.province, //省份
				city: userInfo.city, //市
				appid: userInfo.appid,
				appname: userInfo.appname,
				_add_time: new Date().getTime()
			})

			res.balance = updateUser.balance
		}

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
}
